package top.v5it.japi.ddd.core.dao.impl;

import cn.hutool.core.lang.func.Func1;
import cn.hutool.core.lang.func.LambdaUtil;
import cn.hutool.core.util.StrUtil;
import lombok.AccessLevel;
import lombok.Getter;
import lombok.RequiredArgsConstructor;
import top.v5it.japi.ddd.core.util.BeanUtils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 包装sql语句
 *
 * @author zhanpu
 * @date 2023/4/3
 */
@Getter(AccessLevel.PROTECTED)
public abstract class Wrapper<T> {

    private final T entity;
    private final List<Condition> conditions;
    private final Map<String, Object> segments;
    private final List<String> columnSegments;
    private final Map<String, Object> value;

    protected Wrapper(T entity) {
        this.entity = entity;
        this.conditions = new ArrayList<>();
        this.segments = new HashMap<>();
        this.columnSegments = new ArrayList<>();
        this.value = new HashMap<>();
    }

    protected void addSegment(String key, Object value) {
        this.segments.put(key, value);
    }

    protected void addCondition(Condition condition) {
        this.conditions.add(condition);
    }

    protected void addColumnSegment(String segment) {
        this.columnSegments.add(segment);
    }

    protected void addValue(String key, Object value) {
        this.value.put(key, value);
    }

    protected String mapper(Func1<T, ?> columnFunc) {
        return LambdaUtil.getFieldName(columnFunc);
    }

    protected Entry resolve(Func1<T, ?> columnFunc) {
        final String fieldName = LambdaUtil.getFieldName(columnFunc);
        final Object value = BeanUtils.getValueByField(getEntity(), fieldName);
        return new Entry(fieldName, value);
    }

    protected String getSql() {
        return StrUtil.EMPTY;
    }

    @Getter
    @RequiredArgsConstructor
    protected static class Entry {
        private final String name;
        private final Object value;
    }

}
